<?php

namespace statistics\controller;

use statistics\view\renderers\AbstractPageRenderer;
use statistics\utils\AccessControlManager;
use statistics\view\renderers\StandardPageRenderer;
use statistics\view\renderers\ErrorPageRenderer;
use statistics\utils\ScrollPosHandler;
use statistics\utils\HTTPParameterReader;
use statistics\utils\DBAccess;

require_once (substr ( __DIR__, 0, strpos ( __DIR__, 'statistics' ) + 10 ) . DIRECTORY_SEPARATOR . 'includes.php');
abstract class AbstractPageController {
	
	private $controllerId;
	private $pageRenderer;
	private $staDBHandler;
	protected $paramReader;
	protected $scrollPosHandler;
	
	public function __construct($pageTitle) {
		$this->staDBHandler = DBAccess::getInstance();
		$this->pageRenderer = new StandardPageRenderer($pageTitle);
		$this->scrollPosHandler = new ScrollPosHandler();
		$this->paramReader = new HTTPParameterReader();
	}
	protected function setPageRenderer(AbstractPageRenderer $pageRenderer){
		$this->pageRenderer = $pageRenderer;
	}
	public function getControllerId(){
		return $this->controllerId;
	}
	public function constructPage() {
		try {
			$this->staDBHandler->isPluginInstalled(); 
			$this->checkPrivileges ();
			$this->readHTMLParameters ();
			$this->saveCurrentUrlForNavigation();
			$this->processPageData ();
			$this->pageRenderer->addContentElement($this->getRenderableContent());
			$this->pageRenderer->renderPage ();
			echo $this->pageRenderer->getRenderedElementHTML();			
		} catch ( Exception $e ) {
			echo '<h1>Fehlerseite</h1>';
		}
	}
	abstract protected function getRenderableContent();
	abstract protected function getRequiredPrivilege();
	abstract protected function readHTMLParameters();
	abstract protected function processPageData();
	
	protected function checkPrivileges() {
		$hasPrivileges = false;		
		$acm = AccessControlManager::getInstance ();		
		$hasPrivileges = $acm->checkUserPrivilege ( $this->getRequiredPrivilege() );		
		return $hasPrivileges;
	}
	
	protected function saveCurrentUrlForNavigation($removeScrollPos = false){
		global $gNavigation;
		$urlToSave = CURRENT_URL;
		if ($removeScrollPos == true){
			$urlToSave = $this->scrollPosHandler->removeScrollPosFromURL(CURRENT_URL);
		}
		$gNavigation->addUrl($urlToSave);
	}
	
	protected function getPageRenderer(){
		return $this->pageRenderer;
	}
}
?>